package cn.dckeji.gameBox.common.utils;


import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.xiaoleilu.hutool.setting.dialect.Props;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;


import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 微信工具类
 * @author WangDong
 *  2018-04-12 13:15
 */
public class WXUtils {


    private static final Logger LOGGER = Logger.getLogger(WXUtils.class);

    //加载微信配置文件
    private static Props props = new Props("wx.properties", "utf-8");
    private static  String WX_APP_ID_QI_YE = props.getStr("wx.appId");
    private static String WX_APP_SECRET_QI_YE = props.getStr("wx.appSecret");

    /**
     * 获取用户openId
     * @param code
     * @return
     */
    public static Map<String, String> getUserOpenId(String code){
        String WX_APP_ID = "";
        String WX_APP_SECRET = "";

            WX_APP_ID = WX_APP_ID_QI_YE;
            WX_APP_SECRET = WX_APP_SECRET_QI_YE;


        JsonObject object = new JsonObject();
        Map<String, String> data = new HashMap<>();
        try{
            String url = String.format("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                    WX_APP_ID,WX_APP_SECRET, code);
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            String tokens = EntityUtils.toString(httpEntity, "utf-8");
            Gson token_gson = new Gson();
            object = token_gson.fromJson(tokens, JsonObject.class);


            String session_key = object.get("session_key").toString();
            String openid = object.get("openid").toString();
            data.put("sessionKey",session_key);
            data.put("openId",openid);

        }catch(Exception e){
            e.printStackTrace();
            LOGGER.error("fail to request wechat openid. [error={" + e + "}]");
        }
        return data;
    }


    /**
     * 获access_token
     *
     * @return
     */
    public static String getAccessToken(Integer type) {
        String WX_APP_ID = "";
        String WX_APP_SECRET = "";
            WX_APP_ID = WX_APP_ID_QI_YE;
            WX_APP_SECRET = WX_APP_SECRET_QI_YE;
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                + WX_APP_ID + "&secret=" + WX_APP_SECRET;

        LOGGER.info("request user info from url: {" + url + "}");
        JsonObject accessTokenInfo = null;
        try {

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            String response = EntityUtils.toString(httpEntity, "utf-8");
            System.out.println("获取Token-------------------"+response);
            Gson token_gson = new Gson();

            accessTokenInfo = token_gson.fromJson(response, JsonObject.class);
            LOGGER.info("get accessTokenInfo success. [result={" + accessTokenInfo + "}]");

            return accessTokenInfo.get("access_token").toString().replaceAll("\"", "");

        } catch (Exception ex) {
            LOGGER.error("fail to request wechat user info. [error={" + ex + "}]");
        }
        return "";
    }



    /**全局Token 获取用户信息
     * 获取用户信息
     *
     * @param accessToken
     * @param openId
     * @return
     */
    public static Map<String, String> getUserInfo(String accessToken, String openId) {

        Map<String, String> data = new HashMap<>();
        // String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN";
        String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN";
        LOGGER.info("request user info from url: {" + url + "}");
        JsonObject userInfo = null;
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            String response = EntityUtils.toString(httpEntity, "utf-8");

            Gson token_gson = new Gson();

            userInfo = token_gson.fromJson(response, JsonObject.class);
            LOGGER.info("get userinfo success. [result={" + userInfo + "}]");

            data.put("openid", userInfo.get("openid").toString().replaceAll("\"", ""));
            data.put("nickname", userInfo.get("nickname").toString().replaceAll("\"", ""));
            data.put("city", userInfo.get("city").toString().replaceAll("\"", ""));
            data.put("province", userInfo.get("province").toString().replaceAll("\"", ""));
            data.put("country", userInfo.get("country").toString().replaceAll("\"", ""));
            data.put("headimgurl", userInfo.get("headimgurl").toString().replaceAll("\"", ""));
        } catch (Exception ex) {
            LOGGER.error("fail to request wechat user info. [error={" + ex + "}]");
        }
        return data;
    }

    /**
     * 去除emoji表情
     * @param source
     * @return
     */
    public static String deleteEmoji(String source) {
        if(StringUtils.isEmpty(source)){
            return "";
        }
        //去掉emoji
        // String pattern="[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]";
        String pattern="(?:[\uD83C\uDF00-\uD83D\uDDFF]|[\uD83E\uDD00-\uD83E\uDDFF]|[\uD83D\uDE00-\uD83D\uDE4F]|[\uD83D\uDE80-\uD83D\uDEFF]|[\u2600-\u26FF]\uFE0F?|[\u2700-\u27BF]\uFE0F?|\u24C2\uFE0F?|[\uD83C\uDDE6-\uD83C\uDDFF]{1,2}|[\uD83C\uDD70\uD83C\uDD71\uD83C\uDD7E\uD83C\uDD7F\uD83C\uDD8E\uD83C\uDD91-\uD83C\uDD9A]\uFE0F?|[\u0023\u002A\u0030-\u0039]\uFE0F?\u20E3|[\u2194-\u2199\u21A9-\u21AA]\uFE0F?|[\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55]\uFE0F?|[\u2934\u2935]\uFE0F?|[\u3030\u303D]\uFE0F?|[\u3297\u3299]\uFE0F?|[\uD83C\uDE01\uD83C\uDE02\uD83C\uDE1A\uD83C\uDE2F\uD83C\uDE32-\uD83C\uDE3A\uD83C\uDE50\uD83C\uDE51]\uFE0F?|[\u203C\u2049]\uFE0F?|[\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE]\uFE0F?|[\u00A9\u00AE]\uFE0F?|[\u2122\u2139]\uFE0F?|\uD83C\uDC04\uFE0F?|\uD83C\uDCCF\uFE0F?|[\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA]\uFE0F?)";
        String reStr = "";
        Pattern emoji=Pattern.compile(pattern);
        Matcher emojiMatcher=emoji.matcher(source);
        String s = emojiMatcher.replaceAll(reStr);
        return s;
    }


    /**
     * xml转map
     *
     * @param xmlString
     * @return
     */
    public static Map xmlToMap(String xmlString) {
        Document document = null;
        Map map = new HashMap();
        try {
            document = DocumentHelper.parseText(xmlString);
            Element rootElement = document.getRootElement();
            // 得到根元素的所有子节点
            List<Element> elementList = rootElement.elements();

            // 遍历所有子节点
            for (Element e : elementList) {
                map.put(e.getName(), e.getText());
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return map;
    }
}
